<?php

/**
 * +----------------------------------------------------------------------
 * | 后台页面
 * | 需要验证登录信息
 * | 应用 plugin/DferThinkcmfTools
 * | 控制器 AdminIndex
 * +----------------------------------------------------------------------
 *                                            ...     .............
 *                                          ..   .:!o&*&&&&&ooooo&; .
 *                                        ..  .!*%*o!;.
 *                                      ..  !*%*!.      ...
 *                                     .  ;$$!.   .....
 *                          ........... .*#&   ...
 *                                     :$$: ...
 *                          .;;;;;;;:::#%      ...
 *                        . *@ooooo&&&#@***&&;.   .
 *                        . *@       .@%.::;&%$*!. . .
 *          ................!@;......$@:      :@@$.
 *                          .@!   ..!@&.:::::::*@@*.:..............
 *        . :!!!!!!!!!!ooooo&@$*%%%*#@&*&&&&&&&*@@$&&&oooooooooooo.
 *        . :!!!!!!!!;;!;;:::@#;::.;@*         *@@o
 *                           @$    &@!.....  .*@@&................
 *          ................:@* .  ##.     .o#@%;
 *                        . &@%..:;@$:;!o&*$#*;  ..
 *                        . ;@@#$$$@#**&o!;:   ..
 *                           :;:: !@;        ..
 *                               ;@*........
 *                       ....   !@* ..
 *                 ......    .!%$! ..     | AUTHOR: dfer
 *         ......        .;o*%*!  .       | EMAIL: df_business@qq.com
 *                .:;;o&***o;.   .        | QQ: 3504725309
 *        .;;!o&****&&o;:.    ..          | WEBSITE: http://www.dfer.site
 * +----------------------------------------------------------------------
 *
 */

namespace plugins\dfer_thinkcmf_tools\controller;

use think\Validate;
use app\admin\model\{ThemeFileModel, ThemeModel, PluginModel};
use plugins\dfer_thinkcmf_tools\model\{AdminMenuModel, GuestbookModel, BtSiteModel};
use Dfer\Tools\Statics\{Common};
use Dfer\Tools\Bt;
use plugins\dfer_thinkcmf_tools\{Constants};

/**
 * 会自动添加菜单，正式环境可以手动隐藏
 * @adminMenuRoot(
 *     'name'   =>'dfer工具包',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 99,
 *     'icon'   =>'star',
 *     'remark' =>''
 * )
 */
class AdminIndexController extends AdminBaseController
{
    private $session_config, $cookie_config, $env_config;
    protected function initialize()
    {
        parent::initialize();
        $this->session_config = CMF_DATA . "config" . DIRECTORY_SEPARATOR . "session.php";
        $this->cookie_config  = CMF_DATA . "config" . DIRECTORY_SEPARATOR . "cookie.php";
        $this->env_config     = CMF_ROOT . ".env";
    }


    // ###################################### 插件子菜单 START ######################################    
    /**
     * 插件管理默认方法
     * 菜单操作 plugin/DferThinkcmfTools/AdminIndex/index
     * @adminMenu(
     *     'name'   => '管理',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 1,
     *     'icon'   => '',
     *     'remark' => 'http://{domain name}/plugin/dfer_thinkcmf_tools/admin_index/index',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $this->assign("tab", $this->request->param('tab') ?: 'plugins_name');
        $this->assign("session_content", file_exists($this->session_config) ? file_get_contents($this->session_config) : "");
        $this->assign("cookie_content", file_exists($this->cookie_config) ? file_get_contents($this->cookie_config) : "");
        $this->assign("env_content", file_exists($this->env_config) ? file_get_contents($this->env_config) : "");
        $status = array("1" => lang('Enable'), "0" => lang('Disable'));
        $this->assign("status", $status);        

        // 登录过期时间
        $session_content_demo = <<<STR
        <?php
        return [
            'name' => 'PHPSESSID',
            'expire' =>60*60*24*5
        ]; 
        STR;
        $this->assign("session_content_demo", Common::html($session_content_demo));

        $cookie_content_demo = <<<STR
        <?php
        return [
            'expire' =>60*60*24*5
        ];
        STR;
        $this->assign("cookie_content_demo", Common::html($cookie_content_demo));

        // 调试
        $env_content_demo = <<<STR
        APP_DEBUG = 1
        STR;
        $this->assign("env_content_demo", Common::html($env_content_demo));
        $this->assign("v8", $this->checkVersion(Constants::V8));
        // if($this->checkVersion(self::V8)){
        //     return $this->view(__FUNCTION__);            
        // }

        // 日志
        $log_src = Common::str("{root}/data/logs/{0}/{1}.log", [date('Ym'), date('d'), "root" => Common::getRootPath()]);
        $this->assign("log_content", Common::readFile($log_src));

        $panel_host =  config('bt.panel_host');
        $site_list  = static::btService()->siteList();
        // var_dump($site_list);
        $this->assign("panel_host", $panel_host);
        $this->assign("site_list", $site_list);

        return $this->fetch(__FUNCTION__);
    }

    /**
     * https://www.thinkcmf.com/docs/cmf8/#/%E6%8F%92%E4%BB%B6%E9%85%8D%E7%BD%AE
     * @adminMenu(
     *     'name'   => '设置',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 2,
     *     'icon'   => '',
     *     'remark' => '',
     *     'param'  => ''
     * )
     */
    public function setting($var = null)
    {
        $id = $this->info['id'];

        $pluginModel = new PluginModel();
        $plugin      = $pluginModel->find($id);

        if (empty($plugin)) {
            $this->error('插件未安装!');
        }

        $plugin = $plugin->toArray();

        $pluginClass = cmf_get_plugin_class($plugin['name']);
        if (!class_exists($pluginClass)) {
            $this->error('插件不存在!');
        }

        $pluginObj = new $pluginClass;
        //$plugin['plugin_path']   = $pluginObj->plugin_path;
        //$plugin['custom_config'] = $pluginObj->custom_config;
        $pluginConfigInDb = $plugin['config'];
        $plugin['config'] = include $pluginObj->getConfigFilePath();
        // var_dump($pluginConfigInDb);
        if ($pluginConfigInDb) {
            $pluginConfigInDb = $this->checkVersion(Constants::V8) ? $pluginConfigInDb : json_decode($pluginConfigInDb, true);
            foreach ($plugin['config'] as $key => $value) {
                if ($value['type'] != 'group') {
                    if (isset($pluginConfigInDb[$key])) {
                        $plugin['config'][$key]['value'] = $pluginConfigInDb[$key];
                    }
                } else {
                    foreach ($value['options'] as $group => $options) {
                        foreach ($options['options'] as $gkey => $value) {
                            if (isset($pluginConfigInDb[$gkey])) {
                                $plugin['config'][$key]['options'][$group]['options'][$gkey]['value'] = $pluginConfigInDb[$gkey];
                            }
                        }
                    }
                }
            }
        }
        // var_dump($plugin['config']);
        extract($plugin['config']);
        $plugin['config'] = [
            'base_setup' => compact('custom_asset_status', 'theme_name', 'update_app_list'),
            'admin_login_page' => compact('custom_login_status', 'title', 'captcha_id', 'private_key'),
            'sms' => compact('sms_type','ali_info','ali_access_key_id', 'ali_access_key_secret', 'ali_sign_name', 'ali_template_code', 'ali_code_key', 'ali_expire_minute','smsbao_info','smsbao_user','smsbao_pwd','smsbao_sign','smsbao_template_id'),
        ];
        $this->assign('data', $plugin);
        $this->assign('id', $id);
        $this->assign("tab", $this->request->param('tab') ?: 'base_setup');
        return $this->fetch(__FUNCTION__);
    }

    public function settingPost()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', 0, 'intval');

            $pluginModel = new PluginModel();
            $plugin      = $pluginModel->find($id)->toArray();

            if (!$plugin) {
                $this->error('插件未安装!');
            }

            $pluginClass = cmf_get_plugin_class($plugin['name']);
            if (!class_exists($pluginClass)) {
                $this->error('插件不存在!');
            }

            $pluginObj = new $pluginClass;
            //$plugin['plugin_path']   = $pluginObj->plugin_path;
            //$plugin['custom_config'] = $pluginObj->custom_config;
            $pluginConfigInDb = $plugin['config'];
            $plugin['config'] = include $pluginObj->getConfigFilePath();

            $rules    = [];
            $messages = [];

            foreach ($plugin['config'] as $key => $value) {
                if ($value['type'] != 'group') {
                    if (isset($value['rule'])) {
                        $rules[$key] = $this->_parseRules($value['rule']);
                    }

                    if (isset($value['message'])) {
                        foreach ($value['message'] as $rule => $msg) {
                            $messages[$key . '.' . $rule] = $msg;
                        }
                    }
                } else {
                    foreach ($value['options'] as $group => $options) {
                        foreach ($options['options'] as $gkey => $value) {
                            if (isset($value['rule'])) {
                                $rules[$gkey] = $this->_parseRules($value['rule']);
                            }

                            if (isset($value['message'])) {
                                foreach ($value['message'] as $rule => $msg) {
                                    $messages[$gkey . '.' . $rule] = $msg;
                                }
                            }
                        }
                    }
                }
            }

            $config = $this->request->param('config/a');

            $validate = new Validate($rules, $messages);
            $result   = $validate->check($config);
            if ($result !== true) {
                $this->error($validate->getError());
            }

            $pluginModel = PluginModel::where('id', $id)->find();
            $pluginModel->save(['config' => $this->checkVersion(Constants::V8) ? $config : json_encode($config)]);
            cmf_clear_cache();
            $this->success(lang('EDIT_SUCCESS'), '');
        }
    }

    /**
     * 解析插件配置验证规则
     * @param $rules
     * @return array
     */
    private function _parseRules($rules)
    {
        $newRules = [];

        $simpleRules = [
            'require',
            'number',
            'integer',
            'float',
            'boolean',
            'email',
            'array',
            'accepted',
            'date',
            'alpha',
            'alphaNum',
            'alphaDash',
            'activeUrl',
            'url',
            'ip'
        ];
        foreach ($rules as $key => $rule) {
            if (in_array($key, $simpleRules) && $rule) {
                array_push($newRules, $key);
            }
        }

        return $newRules;
    }

    /**
     * 显示所有菜单
     * @adminMenu(
     *     'name'   => '菜单列表',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10,
     *     'icon'   => '',
     *     'remark' => 'http://{domain name}/plugin/dfer_thinkcmf_tools/admin_index/menuList',
     *     'param'  => ''
     * )
     */
    public function menuList()
    {
        $adminMenuModel = new AdminMenuModel();
        $menus          = $adminMenuModel->menuTree();
        $this->assign("menus", $menus);
        return $this->fetch(__FUNCTION__);
    }

    /**
     * 查看留言
     * 菜单操作 plugin/DferThinkcmfTools/AdminIndex/messageBoard
     * @adminMenu(
     *     'name'   => '留言列表',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => 'http://{domain name}/plugin/DferThinkcmfTools/AdminIndex/messageBoard',
     *     'param'  => ''
     * )
     */
    public function messageBoard($var = null)
    {
        $datas = GuestbookModel::order('id desc')->paginate();
        $this->assign("datas", $datas);
        $this->assign('page', $datas->render());
        return $this->fetch(__FUNCTION__);
    }
    // ######################################  插件子菜单 END  ######################################

    // ###################################### 管理 START ######################################
    // ********************** 数据清理 START **********************    
    /**
     * 清除模板数据
     */
    public function clearThemeMorePost()
    {
        $ret        = ThemeFileModel::where('theme', $this->config['theme_name'])->update(['more' => '', 'config_more' => '']);
        $themeModel = new ThemeModel();
        $themeModel->updateTheme($this->config['theme_name']);
        cmf_clear_cache();
        if ($ret)
            $this->success('清除成功', cmf_plugin_url('DferThinkcmfTools://AdminIndex/index', ['tab' => 'data_clear']), null, 0);
        else
            $this->error('不需要清除', cmf_plugin_url('DferThinkcmfTools://AdminIndex/index', ['tab' => 'data_clear']), null, 0);
    }
    // **********************  数据清理 END  **********************

    // ********************** 后台登录过期时间 START **********************
    /**
     * 设置session配置文件
     */
    public function setSessionConfig()
    {
        // var_dump($this->request->param());die;
        $session_content = Common::html($this->request->param('session_content'), false);
        // var_dump($session_content);die;
        $to   = $this->session_config;
        $to   = Common::formatDirectorySeparator($to);
        Common::mkDirs(dirname($to));
        $ret = file_put_contents($to, $session_content);

        if ($this->request->param('cookie_content')) {
            $cookie_content = Common::html($this->request->param('cookie_content'), false);
            $to             = $this->cookie_config;
            $ret            = file_put_contents($to, $cookie_content);
        }

        if ($ret)
            $this->success('设置成功', cmf_plugin_url('DferThinkcmfTools://AdminIndex/index', ['tab' => 'admin_login_expire']), null, 0);
        else
            $this->error('不需要设置', cmf_plugin_url('DferThinkcmfTools://AdminIndex/index', ['tab' => 'admin_login_expire']), null, 0);
    }
    // **********************  后台登录过期时间 END  **********************

    // ********************** 调试功能 START **********************
    /**
     * 设置env配置文件
     */
    public function setEnvConfig()
    {
        $env_content   = Common::html($this->request->param('env_content'), false);
        $to            = $this->env_config;
        $to            = Common::formatDirectorySeparator($to);
        Common::mkDirs(dirname($to));
        $ret = file_put_contents($to, $env_content);

        if ($this->request->param('env_content')) {
            $env_content = Common::html($this->request->param('env_content'), false);
            $to          = $this->env_config;
            $ret         = file_put_contents($to, $env_content);
        }

        if ($ret)
            $this->success('设置成功', cmf_plugin_url('DferThinkcmfTools://AdminIndex/index', ['tab' => 'debugging_function']), null, 0);
        else
            $this->error('不需要设置', cmf_plugin_url('DferThinkcmfTools://AdminIndex/index', ['tab' => 'debugging_function']), null, 0);
    }
    // **********************  调试功能 END  **********************

    // ********************** 宝塔服务管理 START **********************
    /**
     * bt站点设置
     */
    public function siteSetup()
    {
        $site_id = $this->request->param('site_id', 0, 'intval');
        $item_data_db = BtSiteModel::where('site_id', $site_id)->find();
        $this->assign('site_id', $site_id);

        $item_data = [
            "site_status" => [
                "title"  => "站点状态",
                "type"   => "select",
                "value"  => 0,
                "options" => [
                    "0" => "正常",
                    "100" => "维护"
                ],
                "tip" => "开启维护之后，进入维护页面"
            ],
            'maintenance_time' => [
                'title' => '维护截止时间',
                'type'  => 'datetime',
                'value' => Common::getTime(time() + 60 * 60 * 3),
                'tip'   => '关闭站点的截止时间'
            ],
            'maintenance_logo'     => [
                'title' => '维护页面logo',
                'type'  => 'text',
                'value' => Constants::LOGO,
                'tip'   => '维护页面的logo地址或base64字符串。比如：`/assets/images/logos/logo-1.png`'
            ],
        ];

        if ($item_data_db) {
            foreach ($item_data as $key => $value) {
                if ($value['type'] != 'group') {
                    if (isset($item_data_db[$key])) {
                        $item_data[$key]['value'] = $item_data_db[$key];
                    }
                } else {
                    foreach ($value['options'] as $group => $options) {
                        foreach ($options['options'] as $gkey => $value) {
                            if (isset($item_data_db[$gkey])) {
                                $item_data[$key]['options'][$group]['options'][$gkey]['value'] = $item_data_db[$gkey];
                            }
                        }
                    }
                }
            }
        }
        // var_dump($item_data);
        $this->assign('item_data', $item_data);

        return $this->fetch(__FUNCTION__);
    }

    public function siteSetupPost()
    {
        if ($this->request->isPost()) {
            $site_id = $this->request->param('site_id', 0, 'intval');
            $data = $this->request->param('config/a');
            $data['site_id'] = $site_id;
            $model = BtSiteModel::where('site_id', $site_id)->find();
            // var_dump($data);

            // var_dump($data);
            if ($model) {
                $model->save($data);
            } else {
                $data['site_path'] = static::btService()->sitePath($site_id);
                $data['run_path'] = static::btService()->dirUserIni($site_id, $data['site_path'])['runPath']['runPath'];
                $model = BtSiteModel::create($data);
            }

            switch ($data['site_status']) {
                case '100':
                    // 创建页面
                    $targetDir = Common::str("{root}/data/maintenance/{name}", ["root" => Common::getRootPath(), 'name' => $site_id]);
                    Common::copyDir($this->root . "/view/public/assets/js", "{$targetDir}/js", true);
                    Common::copyDir($this->root . "/view/public/assets/css", "{$targetDir}/css", true);
                    $file = "{$targetDir}/index.php";
                    $content = Common::str(Common::readFile($this->root . "/view/maintenance.tmpl.html"), [
                        'title' => "网站正在维护!",
                        'logo' => $data['maintenance_logo'],
                        'date' => $data['maintenance_time'],
                    ]);
                    Common::writeFile($content, $file);
                    // 更改目录
                    static::btService()->sitePathUpdate($site_id, dirname($file));
                    // var_dump($file,$ret);
                    break;
                default:
                    if (isset($model['site_path']))
                        static::btService()->sitePathUpdate($site_id, $model['site_path']);
                    if (isset($model['run_path']))
                        static::btService()->siteRunPathUpdate($site_id, $model['run_path']);
                    break;
            }


            $this->success(lang('EDIT_SUCCESS'));
        }
    }

    /**
     * bt服务
     * @param object $var 变量
     * @return mixed
     **/
    public static function btService($var = null)
    {
        // bt管理
        $panel_host =  config('bt.panel_host');
        $secret_key =  config('bt.secret_key');
        $bt         = new Bt(compact('panel_host', 'secret_key'));
        return $bt;
    }
    // **********************  宝塔服务管理 END  **********************

    // ######################################  管理 END  ######################################
}
